package jtg.model;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CalculateHash {
	private static final String hash="SHA-1";
	private static String codeHash="SHA1";

	public static String calcoloHash(String filename){
		try {
			MessageDigest md = MessageDigest.getInstance(hash);
			FileInputStream fis = new FileInputStream(filename);
			byte[] dataBytes = new byte[1024];
			int nread = 0; 
			while ((nread = fis.read(dataBytes)) != -1) {
				md.update(dataBytes, 0, nread);
			};
			byte[] mdbytes = md.digest();

			//convert the byte to hex format method 1
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < mdbytes.length; i++) {
				sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
			}
			return sb.toString().toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String inserisciHash(String xmlFile,String file_old,String file_new,String hash){
		Pattern p = Pattern.compile(file_old+".xsl[?]"+codeHash+"=[A-Z0-9]*");
		Matcher m = p.matcher(xmlFile);
		boolean result=m.find();
		String out="";
		if(result) {

			out=m.replaceFirst(file_new+".xsl?"+codeHash+"="+hash);;
		}
		return out;
	}
}
